<?php
namespace Api\Model;
use Think\Model;
/**
 * @todo  API订单模型
 * @since 2015-8-19
 */
class OrderModel extends Model{
    
    private $activity_id = 22;

    /**
     * @todo    外部写入订单API（MODEL）
     * @param   int     phone_number 手机号
     * @param   float   amount  支付金额
     * @param   text    remark  备注信息（原价，成交价，已付定金，商品信息）
     * @return  成功:{"status":1,"info":"创建订单ID"} 失败:{"status":0,"info":"错误信息"}
     * @author  fang
     */
    public function orderBuild($map){
        //活动ID
        //$activity_id = (C('JJHH_ACTIVITY_ID') > 0)? C('JJHH_ACTIVITY_ID') : 0 ;
        if(NOW_TIME < 1448121600){  //2015/11/22
            $activity_id = 23;
        }else{
            $activity_id = $this->activity_id;
        }
        
        $amount = (float)$map['amount'];
        $remark= strip_tags($map['remark']);
        $phone = trim($map['phone_number']);
        $shop_id = (int)$map['shop_id'];
        if($amount <= 0){
            $this->error = 'amount参数错误';
            return false;
        }
        if(empty($remark)){
            $this->error = 'remark参数错误';
            return false;
        }
        if($shop_id == 0){
            $this->error = 'shop_id参数错误';
            return false;
        }
        //识别码
        try {
            if(preg_match('/^1[3-8][0-9]{9}$/', $phone) ){
                $customer_id = D('Admin/Customer','Service')->customerIsJoinActivity($activity_id,$phone,'');
                if($customer_id == 0){
                    $this->error = $activity_id . D('Admin/Customer','Service')->getError();
                    return false;
                }
            }else{
                $this->error = 'phone参数错误';
                return false;
            }
            $data = array(
                'activity_id' => (int)$activity_id,//线上支付依据线下家博会活动ID写入
                'customer_id' => (int)$customer_id,//用户ID
                'shop_id' => $shop_id,//店铺ID
                'order_amount' => $amount,//当前订单金额
                'order_pay_amount' => $amount,//订单支付金额
                'remark' => $remark,//商品信息备注(店铺,品类,商品介绍等)
                'order_status' => 0,//先创建（0）后回调（1/2）1:支付失败 2:支付成功(已付款)
                'order_type' => 2,//2:线上订单
                'check_code' => mt_rand(100000,999999),
                'create_time' => NOW_TIME,
            );
            $add = M('order')->add($data);
            //日志记录
            $log_add = D('Admin/Order')->orderLogAdd($add);
            if($add === false){
                $this->error = '订单生成失败';
                return false;
            }
            return $add;
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }
    
    /**
     * @todo    天天特卖写入订单API（MODEL）
	 * @param   int     activity_id 活动id（正常：－1；促销：－2；团购：－3）
	 * @param   int     customer_id 用户id
	 * @param   int     goods_id 商品id
	 * @param   int     merchant_id 商户id
	 * @param   int     shop_id 店铺id
	 * @param   int     goods_category_id 商品品类id
	 * @param   char    goods_name 商品名称
	 * @param   char    goods_title 商品副标题
	 * @param   char    goods_introduction 商品简介
	 * @param   double  market_price 市场价格
	 * @param   double  shop_price 商城价格
	 * @param   double  promotion_price 促销价格
	 * @param   char    goods_unit 单位
	 * @param   double  goods_deposit 定金
	 * @param   int     pic_id 封面图
	 * @param   text    goods_content 商品介绍
	 * @param   int     goods_type 类型：0:正常销售1:促销
	 * @param   int     position 位置
	 * @param   float   amount  支付金额
     * @return  成功:{"status":1,"info":"创建订单ID"} 失败:{"status":0,"info":"错误信息"}
     * @author  fang
     */
    public function saleOrderBuild($map){
        if($map['customer_id'] <= 0){
            $this->error = 'customer_id参数错误';
            return false;
        }
        if($map['goods_id'] <= 0 || $map['merchant_id'] <= 0 || $map['shop_id'] <= 0 || $map['goods_category_id'] <= 0){
            $this->error = '商品属性参数错误';
            return false;
        }
        if(empty($map['goods_name']) || empty($map['goods_title']) || empty($map['goods_content'])){
            $this->error = '商品描述参数错误';
            return false;
        }
        if($map['pic_id'] <= 0){
            $this->error = '封面图参数错误';
            return false;
        }
        if($map['amount'] <= 0){
            $this->error = 'amount参数错误';
            return false;
        }
        try {
            M('order')->startTrans();
            //订单写入
            $data = array(
                'activity_id' => $map['activity_id'],//正常：－1；促销：－2；团购：－3
                'generalize_member_id' => getGeneralizeMemberId(),//推广人
                'customer_id' => $map['customer_id'],//用户id
                'shop_id' => $map['shop_id'],//店铺id
                'goods_id' => $map['goods_id'],//商品id
                'order_amount' => $map['amount'],//当前订单金额
                'order_pay_amount' => $map['amount'],//订单支付金额
                'order_status' => 0,//先创建（0）后回调（1/2）1:支付失败 2:支付成功(已付款)
                'order_type' => 2,//2:线上订单
                'check_code' => mt_rand(100000,999999),
                'create_time' => NOW_TIME,
                'remark' => ''
            );
            $add = M('order')->add($data);
            //快照写入
            $snap_data = array(
                'order_id' => (int)$add,
                'activity_id' => $map['activity_id'],//天天特卖活动ID
                'goods_id' => $map['goods_id'],//商品id
                'shop_id' => $map['shop_id'],//店铺id
                'merchant_id' => $map['merchant_id'],//商户id
                'goods_category_id' => $map['goods_category_id'],//商品二级品类id
                'goods_category_pid' => $map['goods_category_pid'],//商品一级品类id
                'customer_id' => $map['customer_id'],//用户id
                'goods_name' => $map['goods_name'],//商品名称
                'goods_title' => $map['goods_title'],//商品副标题
                'goods_introduction' => $map['goods_introduction'],//商品简介
                'market_price' => $map['market_price'],//市场价格
                'shop_price' => $map['shop_price'],//商城价格
                'promotion_price' => $map['promotion_price'],//促销价格
                'goods_unit' => $map['goods_unit'],//单位
                'goods_deposit' => $map['goods_deposit'],//定金
                'pic_id' => $map['pic_id'],//封面图
                'goods_content' => $map['goods_content'],//商品介绍
                'goods_type' => $map['goods_type'],//类型：0:正常1:促销
                'goods_recommend' => $map['position'],//推荐：0:正常1:推荐
                'create_time' => NOW_TIME
            );
            $snap_add = M('order_goods_snapshot')->add($snap_data);
            //事务处理
            if($add === false || $snap_add === false){
                M('order')->rollback();
                $this->error = '订单生成失败';
                return false;
            }else{
                M('order')->commit();
                //日志记录
                $log_add = D('Admin/Order')->orderLogAdd($add);
                return $add;
            }
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }
    
    /**
     * @todo   订单查询（商户列表）
	 * @param   merchant_id     商户ID
	 * @param   shop_id         店铺ID
     * @param   phone_number    手机号
     * @param   page            页数
     * @author fang
     */
    public function getShopOrderList($map){
    
        $listRows = 50;
        $start = $map['page']*$listRows;
        //根据商户筛选
        $where['merchant_id'] = (int)$map['merchant_id'];
        //根据活动筛选
        if($map['activity_id'] != 0){
            $where['activity_id'] = $map['activity_id'];
        }
        //根据状态筛选
        if($map['order_status'] > 0){
            $where['order_status'] = (($map['order_status'] == 2))? array('in','2,4'): $map['order_status'] ;
        }else{
            //商户默认的订单列表（2:已付款(未申请);4:已消费(未申请);5:申请核销(处理中);7:已结算(已返款);3:已退款(已退款)）
            $where['order_status'] = array('in','2,3,4,5,7');
        }
        //根据店铺筛选
        if($map['shop_id'] > 0){
            $where['shop_id'] = $map['shop_id'];
        }
        //根据纸质订单筛选
        if($map['paper_order'] > 0){
            $where['paper_order'] = $map['paper_order'];
            //有纸质订单条件时:线上订单
            $where_order['paper_order'] = $map['paper_order'];
            $where_order['order_type'] = 2;
            $order_type = M('order')->where($where_order)->getField('order_type');
            if($order_type == 2){
                unset($where['merchant_id']);
            }
        }else{
            //商户后台只显示已绑定纸质订单的线上订单
            $where['paper_order'] = array('gt', 0);
        }
        //订单时间
        if($map['start_time'] > 0){
            $where['create_time'] = array('between', array($map['start_time'], $map['end_time']));
        }
        //申请核销时间
        if($map['apply_start_time'] > 0){
            $where['apply_time'] = array('between', array($map['apply_start_time'], $map['apply_end_time']));
        }
        //返款时间
        if($map['back_start_time'] > 0){
            $where['back_time'] = array('between', array($map['back_start_time'], $map['back_end_time']));
        }
        
        $order = 'order_id desc';
        $count = D('Admin/OrderShopView')->where($where)->count();
        $list = D('Admin/OrderShopView')->where($where)->limit($start,$listRows)->order($order)->select();
        if($list){
            $row_count = count($list);
            for ($i=0;$i<$row_count;$i++){
                $list[$i]['phone_number'] = getCustomerName($list[$i]['customer_id']);
                $list[$i]['shop_name'] = getShopName($list[$i]['shop_id']);
                $list[$i]['conf_category'] = getConfCategoryName($list[$i]['conf_category_id']);
                $list[$i]['merchant_name'] = getShopName($list[$i]['merchant_id']);
                $list[$i]['order_status_id'] = $list[$i]['order_status'];
                $list[$i]['order_status'] = get_type_title_merchant($list[$i]['order_status']);
                $list[$i]['order_type'] = get_order_type_title($list[$i]['order_type']);
                $list[$i]['create_time'] = time_format($list[$i]['create_time']);
                $list[$i]['apply_time'] = time_format($list[$i]['apply_time']);
                $list[$i]['back_time'] = time_format($list[$i]['back_time']);
            }
            $data = array(
                'count' => $count,
                'list' => $list,
            );
            return $data;
        }else{
            $this->error = '暂无数据';
            return false;
        }
    
    }
    
    /**
     * @todo    订单申请核销（商户版）
     * @param   order_id        订单ID
	 * @param   merchant_id    商户ID
     * @param   
     */
    public function applyAccount($map){
        //订单ID+商户ID
        $where['order_id'] = $map['order_id'];
        $order = M('order')->field('order_amount,check_code,order_status')->where($where)->find();
        //只能申请核销已付款与与消费状态的订单
        if($order['order_status'] != 2 && $order['order_status'] != 4){
            $this->error = '订单状态无法进行申请核销：'.(int)$order['order_status'];
            return false;
        }
        if($order['check_code'] != $map['check_code'] && $map['check_code'] != 0){
            $this->error = '订单识别码错误：'.(int)$map['check_code'];
            return false;
        }
        //申请核销：5
        $data['order_status'] = 5;
        $data['apply_time'] = NOW_TIME;
        $result = M('order')->where($where)->save($data);
        if($result !== false){
            D('Admin/Order')->orderLogAdd($map['order_id'], $order['order_amount'], 0, 5);//5申请核销
            return true;
        }else{
            $this->error = '申请核销失败，请联系管理员';
            return false;
        }
    }
    
    /**
     * @todo    获取活动列表
     */
    public function getActivityList(){
        return D('Admin/ServiceApi')->getServiceActivity('1,2,3,4');
    }
    
    /**
     * @todo    获取商户的店铺列表
     */
    public function getMerchantShopList($activity_id, $merchant_id){
        if($merchant_id == 0){
            $this->error = 'merchant_id参数错误';
            return false;
        }
        if($activity_id == 0){
            $this->error = 'activity_id参数错误';
            return false;
        }

        $where = array(
            'activity_id' => $activity_id,
            'merchant_id' => $merchant_id,
            'status' => 1
        );
        return D('Admin/ShopActivityView')->field('shop_id,shop_name')->where($where)->select();
    }

    /**
     * @todo    订单查询（个人列表）
	 * @param   customer_id     用户id
	 * @param   activity_id     活动id
	 * @param   order_id        订单id
     * @param   page            页数
     * @author  fang
     */
    public function getOrderList($customer_id, $activity_id, $order_id, $page){
        
        if($customer_id <= 0){
            $this->error = 'customer_id参数错误';
            return false;
        }
        $page = ($page < 0)? 0 : (int)$page ;
        $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        $start = $page*$listRows;
        $where['customer_id'] = $customer_id;//用户id
        if($activity_id > 0){
            $where['activity_id'] = $activity_id;
        }
        if($order_id > 0){
            $where['order_id'] = $order_id;
        }
        //商品名称，订单id，支付时间，支付价格，
        $count = M('order')->where($where)->count();
        $field = 'order_id,goods_id,order_amount,order_status,create_time';
        $order_list = M('order')->field($field)->where($where)->limit($start,$listRows)->order('order_id desc')->select();
        $goods_ids = $goods_data = $return_data = array();
        if($order_list){
            $goods_where['goods_id'] = array('in', array_merge(array_unique(array_column($order_list, 'goods_id'))));
            $goods_list = M('order_goods_snapshot')->field('goods_id,goods_name,goods_title')->where($goods_where)->select();
            if($goods_list){
                foreach ($goods_list as $key=>$val){
                    $goods_data[$val['goods_id']] = array(
                        'goods_name' => $val['goods_name'],
                        'goods_title' => $val['goods_title']
                    );
                }
            }
            foreach ($order_list as $key=>$val){
                if(isset($goods_data[$val['goods_id']])){
                    $order_list[$key]['goods_name'] = $goods_data[$val['goods_id']]['goods_name'];
                    $order_list[$key]['goods_title'] = $goods_data[$val['goods_id']]['goods_title'];
                }else{
                    $order_list[$key]['goods_name'] = '';
                    $order_list[$key]['goods_title'] = '';
                }
            }
            $data = array(
                'count' => $count,
                'list' => $order_list,
            );
            return $data;
        }else{
            $this->error = '暂无数据';
            return false;
        }
        
    }
    
    /**
     * @todo    商户登录（根据条件搜索商户信息）
     */
    public function merchantLogin($map){
        if(empty($map)){
            $this->error = '登录参数错误';
            return false;
        }
        $where = $map;
        $where['status'] = 1;
        $field = 'merchant_id,merchant_name,merchant_address,merchant_phone,merchant_fixed_phone';
        $login = M('merchant')->field($field)->where($where)->find();
        if($login){
            return $login;
        }else{
            $this->error = '商户不存在';
            return false;
        }
    }
    
    /**
     * @todo    发送短信
     * @param   stirng  phone   手机号
     */
    public function merchantSms($phone){
        if(empty($phone)){
            $this->error = 'phone参数错误';
            return false;
        }
        //判断是否为商户手机号
        $where = array(
            'merchant_phone' => $phone,
            'status' => 1
        );
        $merchant = M('merchant')->field('merchant_id')->where($where)->find();
        if(empty($merchant)){
            $this->error = '请输入有效的的手机号码';
            return false;
        }
        //发送验证码
        $session_code = session('merchant_code_'.$phone);
        if(empty($session_code)){
            $code = mt_rand(100000, 999999);
            session('merchant_code_'.$phone, $code, 600);
        }else{
            $code = $session_code;
        }
        D('Api/Sms','Service')->sendSms($phone, $code.' 为您的登录验证码（10分钟内有效）');
        return true;
    }
    
    /**
     * @todo    获取订单详情
     * @param   phone_number    手机号 
     * @param   order_id        订单ID
     * @author  fang
     */
    public function getOrderInfo($map){

        $activity_id = $this->activity_id;
        if(empty($map)){
            $this->error = 'order_id参数错误';
            return false;
        }
        
        $data = D('Admin/OrderShopView')->where($map)->find();
        if($data){
            $data['shop_name'] = getShopName($data['shop_id']);
            $data['conf_category'] = getCustomerName($data['conf_category_id']);
            $data['merchant_name'] = getShopName($data['merchant_id']);
            $data['activity_name'] = getActivityName($activity_id);
            $data['order_status'] = get_type_title($data['order_status']);
            $data['order_type'] = get_order_type_title($data['order_type']);
            return $data;
        }else{
            $this->error = '暂无数据';
            return false;
        }
    }
    
    /**
     * @todo    获取订单数据（对外接口）
     */
    public function apiOrderList($start_time, $end_time){
        
        /**
                               需求接口：
            1）订单号，主键，用来判断是否已经导入。 order_id
            2）订单日期，格式为YYYY-MM-DD HH:MM:SS”。 create_time
            3）客户名称，导入时建立客户档案使用。customer_name
            4）客户联系电话，导入时建立客户档案使用。mobile_phone
            5）客户地址，导入时建立客户档案使用。null
            6）客户邮编，导入时建立客户档案使用。null
            7）订金支付方式，生成凭证时判断对应科目使用。
                1:pos机;2:现金;3支付宝;4:财付通;5:支付宝wap;6:微信PC扫码;7:微信JSSDK支付;
            8）订金。导入凭证时使用。
            9）商品编码。null
            10）商品名称。null
            11）商品所属供应商名称。导入凭证时使用。merchant_name
            12）商品数量。1
            13）商品金额。 导入凭证时使用.
                               另：获取JSON时使用的URL包含起止日期，为获取的订单日期的范围。
         */
        $field = 'order_id,customer_id,merchant_id,create_time';
        $where = array();
        //时间判断
        if($start_time > 0 && $end_time > 0 && $start_time <= $end_time){
            $time = $end_time - $start_time;
            if($time > 86400){//一天
                $this->error = '时间范围不能超过一天！';
                return false;
            }else{
                $where['create_time'] = array(array('egt', $start_time), array('lt', $end_time));
            }
        }else{
            $this->error = '时间范围输入错误！';
            return false;
        }
        //获取订单数据
        $list = D('Admin/OrderShopView')->field($field)->where($where)->select();
        $data = array();
        if($list){
            foreach ($list as $key=>$val){
                $data[$key]['order_id'] = $val['order_id'];//订单号
                $data[$key]['create_time'] = time_format($val['create_time']);//订单日期
                $data[$key]['customer_name'] = getCustomerNameNew($val['customer_id']);//客户名称
                $data[$key]['customer_phone'] = getCustomerName($val['customer_id']);//客户联系电话
                $data[$key]['address'] = '';//客户地址
                $data[$key]['zip_code'] = '';//客户邮编
                $data[$key]['pay_type'] = '';//订金支付方式
                $data[$key]['order_amount'] = '';//订金
                $data[$key]['goods_code'] = '';//商品编码
                $data[$key]['goods_name'] = '';//商品名称
                $data[$key]['merchant_name'] = getMerchantName($val['merchant_id']);//商品所属供应商名称
                $data[$key]['goods_number'] = '';//商品数量
                $data[$key]['goods_amount'] = '';//商品金额
            }
        }
        return $data;
    }
    
    /**
     * @param   int     order_status    状态（0:订单创建成功待支付;1:支付失败;2:支付成功(已付款)）
     */
}